package com.jrx.anytxn.param.controller.sms;

import com.google.common.collect.Maps;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.param.dto.sms.PrSmsTemplateTableReq;
import com.jrx.anytxn.param.dto.sms.PrSmsTemplateTableRes;
import com.jrx.anytxn.param.entity.PrSmsTemplateTable;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.sms.ISmsTemplatesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

/**
 * 短信模板配置表
 *
 * @author lbz
 * @date 2019/12/5
 */
@Api(tags = "短信模板参数API接口")
@RestController
@RequestMapping(value = "/param/smsTemplate")
public class SmsTemplatesController {
    private static final Logger logger = LoggerFactory.getLogger(SmsTemplatesController.class);

    @Autowired
    private InfoService infoService;
    @Autowired
    private ISmsTemplatesService iSmsTemplatesService;

    @ApiOperation(value = "根据租户ID和短信模板ID查询短信模板表信息", notes = "根据租户ID和短信模板ID查询短信模板表信息")
    @GetMapping(value = "/{tenantId}/{templateId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "templateId", value = "短信模板ID", required = true)
    })
    public TxnRespResult<PrSmsTemplateTableRes> getById(@NotNull @PathVariable String tenantId, @PathVariable String templateId) {
        TxnRespResult<PrSmsTemplateTableRes> result = new TxnRespResult<>();
        PrSmsTemplateTableRes res;
        try {
            res = iSmsTemplatesService.getByTenIdIdAndTemplateId(String.valueOf(infoService.getUser().getProjectId()), templateId);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "新增短信模板", notes = "新增短信模板")
    @PostMapping("/")
    public TxnRespResult<PrSmsTemplateTableRes> createInterestTable(@RequestBody PrSmsTemplateTableReq prSmsTemplateTableReq) {
        TxnRespResult<PrSmsTemplateTableRes> result = new TxnRespResult<>();
        PrSmsTemplateTableRes res;
        try{
            prSmsTemplateTableReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            prSmsTemplateTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = iSmsTemplatesService.addSmsTemplate(prSmsTemplateTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "分页查询短信模板参数表信息", notes = "分页查询短信模板参数表信息")
    @PostMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true)})
    public TxnRespResult<TxnPage<PrSmsTemplateTableRes>> getAllPageByTenId(@PathVariable("pageNum") Integer pageNum,
                                                                           @PathVariable("pageSize") Integer pageSize,
                                                                           @RequestBody PrSmsTemplateTable req) {
        TxnRespResult<TxnPage<PrSmsTemplateTableRes>> result = new TxnRespResult<>();
        TxnPage<PrSmsTemplateTableRes> response;
        try {
            req.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            response = iSmsTemplatesService.findAllPageByCondition(pageNum, pageSize, req);
            result.getSuccess(response);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "获得短信模板下拉信息", notes = "获得短信模板下拉信息")
    @GetMapping(value = "/list")
    public TxnRespResult<HashMap<String, List<PrSmsTemplateTableRes>>> getAllSmsTemplateList() {
        TxnRespResult<HashMap<String, List<PrSmsTemplateTableRes>>> result = new TxnRespResult<>();
        String tenantId=String.valueOf(infoService.getUser().getProjectId());
        List<PrSmsTemplateTableRes> allTemplate = iSmsTemplatesService.findAllSmsTemplateByTenId(tenantId);
        HashMap<String, List<PrSmsTemplateTableRes>> sysCodeMap = Maps.newHashMap();
        sysCodeMap.put("listData", allTemplate);
        return result.getSuccess(sysCodeMap);
    }

    @ApiOperation(value = "根据租户ID编辑短信模板参数表信息", notes = "根据租户ID编辑短信模板参数表信息")
    @PutMapping("/")
    public TxnRespResult<PrSmsTemplateTableRes> modifySmsTemplate(@RequestBody PrSmsTemplateTableReq request) {
        TxnRespResult<PrSmsTemplateTableRes> result = new TxnRespResult<>();
        PrSmsTemplateTableRes res;
        try {
            request.setUpdateBy(infoService.getUser().getUserName());
            res = iSmsTemplatesService.modifySmsTemplateTable(request);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID和模板ID删除短信模板信息", notes = "根据租户ID和模板ID删除短信模板信息")
    @DeleteMapping(value = "/{tenantId}/{templateId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "templateId", value = "短信模板ID", required = true)
    })
    public TxnRespResult<Boolean> removeByTenIdAndDelqId(@NotNull @PathVariable String tenantId, @PathVariable String templateId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        Boolean flag;
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);

            flag = iSmsTemplatesService.removeByTenantIdAndTemplateId(String.valueOf(infoService.getUser().getProjectId()), templateId);
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID和机构号获取有效短信模板信息", notes = "根据租户ID和机构号获取有效短信模板信息")
    @GetMapping(value = "/list/orgId/{orgId}")
    @ApiImplicitParam(name = "orgId", value = "机构号", required = true)
    public TxnRespResult<HashMap<String, List<PrSmsTemplateTableRes>>> getSmsTemplateListByOrgId(@PathVariable(value = "orgId") String orgId) {
        TxnRespResult<HashMap<String, List<PrSmsTemplateTableRes>>> result = new TxnRespResult<>();

        List<PrSmsTemplateTableRes> templateList;
        try {
            String tenantId =String.valueOf(infoService.getUser().getProjectId());
            templateList = iSmsTemplatesService.findAllSmsTemplateByOrgIdAndTenId(orgId, tenantId);
            HashMap<String, List<PrSmsTemplateTableRes>> sysCodeMap = Maps.newHashMap();
            sysCodeMap.put("listData", templateList);
            result.getSuccess(sysCodeMap);
        } catch (TxnException e) {
            logger.error(e.getMessage(), e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }


}
